import { defineStore } from "pinia";
import type { categoryListType } from "@/api/category";
import {
  reqCategory1List,
  reqCategory2List,
  reqCategory3List,
} from "@/api/category";

//定义store的state类型
export interface categoryStateType {
  category1List: categoryListType;
  category2List: categoryListType;
  category3List: categoryListType;
  category1Id: null | number;
  category2Id: null | number;
  category3Id: null | number;
}
//store的定义
const useCategoryStore = defineStore("category", {
  state: (): categoryStateType => {
    return {
      //三级分类的列表
      category1List: [],
      category2List: [],
      category3List: [],
      //三级分类每一级的id
      category1Id: null,
      category2Id: null,
      category3Id: null,
    };
  },
  actions: {
    //请求一级分类的方法
    async getCategory1List() {
      try {
        const result = await reqCategory1List();
        this.category1List = result;
      } catch (e) {
        return Promise.reject(e);
      }
    },
    //请求二级分类的方法
    async getCategory2List() {
      try {
        const result = await reqCategory2List(this.category1Id as number);
        this.category2List = result;
      } catch (e) {
        return Promise.reject(e);
      }
    },
    //请求三级分类的方法
    async getCategory3List() {
      try {
        const result = await reqCategory3List(this.category2Id as number);
        this.category3List = result;
      } catch (e) {
        return Promise.reject(e);
      }
    },
  },
});

export default useCategoryStore;
